package com.titaniume.sync;


/**
 * @ProjectName: juc
 * @Package: com.titaniume
 * @ClassName: SaleTicket
 * @Author: huangrenfei
 * @Description: Synchronized实现卖票例子 3个售票员 卖票30张
 * @Date: 2021/11/22 10:25
 * @Version: 1.0
 */

//第一 创建资源类，创建属性和操作方法
class Ticket {

    private int number = 30; //票数

    public synchronized void sale() { //买票
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "：卖出:" + (number--) + "剩下:" + number);
        }
    }
}


public class SaleTicket {

    //    第二 创建多线程调用资源类的方法
    public static void main(String[] args) {

        //创建Ticket对象
        Ticket ticket = new Ticket();
        //创建三个线程 卖票
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "AA").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "BB").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "CC").start();


    }


}
